package cn.sourcespro.spring.service.impl;

import cn.sourcespro.spring.dao.UserMapper;
import cn.sourcespro.spring.entity.User;
import cn.sourcespro.spring.service.AuthService;
import cn.sourcespro.spring.service.UserService;
import cn.sourcespro.spring.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/26
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil tokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public User register(User user) {
        String username = user.getUsername();
        User repoUser = userService.findByUsername(username);
        if (repoUser != null) {
            return null;
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userService.add(user);
    }

    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userService.loadUserByUsername(username);
        return tokenUtil.generateToken(userDetails);
    }

    @Override
    public String refresh(String oldToken) {
        String token = oldToken.substring(tokenHead.length()).trim();
        String username = tokenUtil.getUsernameFromToken(token);
        if (StringUtils.isBlank(username)) {
            return null;
        }
        User user = (User) userService.loadUserByUsername(username);
        if (tokenUtil.canTokenBeRefreshed(token)) {
            return tokenUtil.refreshToken(token);
        }
        return null;
    }
}
